using UnityEngine;

public class DeathBringerBattleState : EnemyState
{
    private new DeathBringer Enemy => (DeathBringer)base.Enemy;
    private int moveDirection;

    public DeathBringerBattleState(Enemy enemy, string animName) : base(enemy, animName) { }

    public override void Enter()
    {
        base.Enter();
        if (PlayerManager.Instance.Player.Stats.IsDead)
            StateMachine.ChangeTo(Enemy.Idle);
    }

    public override void Update()
    {
        base.Update();
        if (Enemy.Player)
        {
            stateTimer = Enemy.battleTime;
            if (Vector3.Distance(Enemy.transform.position, Enemy.Player.transform.position) <= Enemy.attackDistance)
            {
                if (CanAttack())
                    StateMachine.ChangeTo(Enemy.Attack);
                else
                    StateMachine.ChangeTo(Enemy.Idle);
            }
        }
        // else
        // {
        //     if (stateTimer <= 0)
        //     {
        //         StateMachine.ChangeTo(Enemy.Idle);
        //     }
        // }
        if (Enemy.Player.transform.position.x > Enemy.transform.position.x)
        {
            moveDirection = 1;
        }
        else if (Enemy.Player.transform.position.x < Enemy.transform.position.x)
        {
            moveDirection = -1;
        }
        if (Enemy.Player && Vector2.Distance(Enemy.Player.transform.position, Enemy.transform.position) < Enemy.attackDistance - 0.1f)
        {
            return;
        }
        Enemy.SetVelocity(moveDirection * Enemy.moveSpeed * 1.5f, Rb.velocity.y);
    }

    private bool CanAttack()
    {
        if (Time.time >= Enemy.lastTimeAttacked + Enemy.attackCooldown)
        {
            Enemy.attackCooldown = Random.Range(Enemy.minAttackCooldown, Enemy.maxAttackCooldown);
            Enemy.lastTimeAttacked = Time.time;
            return true;
        }
        return false;
    }
}
